package com.wyp168.leetcode;

/**
 * @ClassName FindMedianSortedArrays
 * @Description TODO
 * @Author wyp168
 * @Date 2022/7/6 09:04
 */
public class FindMedianSortedArrays {

    public static void main(String[] args) {
        int [] array01 = {1,3,5,7};
        int [] array02 = {4};
        System.out.println(findMedianSortedArrays(array01, array02));
    }


    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int size = nums1.length + nums2.length;

        //定义两个指针，分别表示两个数组的坐标
        int index1 = nums1.length - 1;
        int index2 = nums2.length - 1;
        int [] res = new int[size / 2 + 1];

        int rIndex = size /2;

        while (index1 >= 0 && index2 >= 0 && rIndex != -1) {
            if (nums1[index1] > nums2[index2]) {
                res[rIndex] = nums1[index1];
                index1 --;
                rIndex --;
            } else {
                res[rIndex] = nums2[index2];
                index2 --;
                rIndex --;
            }
        }

        if (rIndex != -1) {
            if (index1 == -1) {
                while (rIndex != -1) {
                    res[rIndex] = nums2[index2];
                    rIndex --;
                    index2 --;
                }
            } else {
                while (rIndex != -1) {
                    res[rIndex] = nums1[index1];
                    rIndex --;
                    index1 --;
                }
            }
        }
        if (size % 2 == 1) {
            return res[0];
        } else {
            return (double)(res[1] + res[0]) / 2;
        }
    }
}
